<template>
  <div class="app-container" :loading="loading">
    <div class="header">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="getRoleListPage"
          />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            clearable
            style="width: 200px"
            @keyup.enter.native="getRoleListPage"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="角色状态"
            clearable
            style="width: 100px"
            @keyup.enter.native="getRoleListPage"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange" style="width: 500px">
          <el-date-picker
            v-model="dateRange"
            style="width: 500px"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getRoleListPage" icon="Search">查询</el-button>
          <el-button icon="Refresh" @click="reset(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button
          type="primary"
          icon="CirclePlus"
          size="default"
          @click="add"
          v-hasPermi="['system:menu:add']"
        >
          新增
        </el-button>

        <el-button
          type="danger"
          icon="Delete"
          size="default"
          :disabled="multiple"
          @click="handleDelete(ids)"
          v-hasPermi="['system:role:edit']"
        >
          删除
        </el-button>

        <el-button
          type="warning"
          icon="Download"
          size="default"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >
          导出
        </el-button>
      </div>
      <div class="table-inner">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column
            label="角色编号"
            prop="roleId"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleName"
            width="150"
            align="center"
          ></el-table-column>
          <el-table-column
            label="权限字符"
            prop="roleKey"
            width="150"
            align="center"
          ></el-table-column>
          <el-table-column
            label="显示顺序"
            prop="roleSort"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column prop="state" label="状态" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                @change="handleChangeStatus(scope.row)"
                active-value="0"
                inactive-value="1"
                active-color="#599e5e"
                inactive-color="red"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            how-overflow-tooltip
            width="180"
          ></el-table-column>
          <el-table-column label="操作" width="270" align="center" fixed="right">
            <template #default="scope">
              <template v-if="scope.row.roleId != 1">
                <el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
                  编辑
                </el-button>
                <el-button
                  @click="handleDelete(scope.row.roleId)"
                  type="danger"
                  size="small"
                  icon="Delete"
                >
                  删除
                </el-button>
                <el-dropdown size="small" placement="bottom-end" style="margin-left: 10px">
                  <el-button type="warning" size="small" icon="DArrowRight">更多</el-button>
                  <template #dropdown>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        icon="CircleCheck"
                        @click="handleOpenScopeDrawer(scope.row)"
                        v-hasPermi="['system:role:edit']"
                      >
                        <span>分配权限</span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        icon="User"
                        v-hasPermi="['system:role:edit']"
                        @click="handleAuthUser(scope.row)"
                      >
                        <span>分配用户</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <!--分页器            -->
        <el-pagination
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :total="total"
          @current-change="getRoleListPage"
          @size-change="getRoleListPage"
        />
      </div>
    </div>
    <RoleDrawer ref="roleDrawer" @getRoleListPage="getRoleListPage" />
    <roleScopeDrawer ref="roleScopeDrawerRef" @getRoleListPage="getRoleListPage" />
  </div>
</template>

<script lang="ts" setup>
  import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
  import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
  import RoleDrawer from './components/roleDrawer.vue'
  import RoleScopeDrawer from './components/roleScopeDrawer.vue'
  import { reqRoleChangeStatusUrl, reqRoleDeleteUrl, reqRolePageList } from '@/api/system/role'
  import { useRouter } from 'vue-router'

  const { proxy }: any = getCurrentInstance()
  const loading = ref(true)
  const roleDrawer = ref()
  const roleScopeDrawerRef = ref()
  // 非单个禁用---判断修改按钮是否可用
  const single = ref(true)
  // 非多个禁用---判断删除按钮
  const multiple = ref(true)
  // 多选框选中数据
  const ids = ref([]) // 非多个禁用
  const total = ref(0) /*总计*/
  const tableData = ref() /*表格的数据*/
  const $router = useRouter()
  /*查询条件*/
  const dateRange = ref([]) /*创建时间*/
  const ruleFormRef = ref<FormInstance>()
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    roleName: '' /*要查询的角色姓名*/,
    roleKey: '' /*查询的角色关键字*/,
    status: '' /*状态*/,
    beginTime: '' /*开始时间*/,
    endTime: '' /*结束时间*/,
  })

  // 分页查询
  const getRoleListPage = async () => {
    loading.value = true
    queryParams.beginTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
    let result = await reqRolePageList(queryParams)
    console.log(result)
    if (result.code == 200) {
      tableData.value = result.data.roleList
      total.value = result.data.total
    } else {
      console.log('查询失败！')
      console.log(result)
    }
    /*将这两个查询参数变成空*/
    queryParams.beginTime = ''
    queryParams.endTime = ''

    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  // 重置
  const reset = (formEl: FormInstance | undefined) => {
    loading.value = true
    proxy.$resetForm(formEl)
    Object.keys(queryParams).forEach((key) => {
      if (key === 'pageNum') queryParams.pageNum = 1
      else if (key === 'pageSize') queryParams.pageSize = 10
      else {
        queryParams[key] = ''
      }
    })
    dateRange.value = []
    /*再次查询*/
    getRoleListPage()
    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  /*多选框*/
  const handleSelectionChange = (selection: any) => {
    console.log('selection', selection)
    ids.value = selection.map((item: any) => item.roleId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  // 添加角色
  const add = () => {
    roleDrawer.value.show()
  }

  // 修改角色
  const edit = (row) => {
    roleDrawer.value.show(row)
  }

  // 批量删除
  const handleDelete = async (roleIds: any) => {
    await proxy.$modal
      .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
      .then(async () => {
        await reqRoleDeleteUrl(roleIds).then((req) => {
          console.log(req)
          if (req.code === 200) {
            proxy.$modal.msgSuccess('删除成功！')
            /*再次进行查找*/
            getRoleListPage()
          } else {
            proxy.$modal.msgError(req.message != null ? req.message : '删除失败!')
            return
          }
        })
      })
      .catch((e: string) => {
        console.log(e)
      })
  }

  //修改角色状态
  const handleChangeStatus = (row) => {
    let text = row.status === '0' ? '启用' : '停用'
    ElMessageBox.confirm(`确定要 ${text} ${row.roleName} 角色吗？`, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        /*发送异步请求*/
        await reqRoleChangeStatusUrl({ roleId: row.roleId, status: row.status })
          .then((req: any) => {
            if (req.code === 200) {
              proxy.$modal.msgSuccess(text + '成功!')
            } else {
              proxy.$modal.msgError(text + '失败！' + req.message)
              row.status = row.status === '0' ? '1' : '0'
            }
          })
          .catch(() => {
            row.status = row.status === '0' ? '1' : '0'
          })
      })
      .catch(() => {
        row.status = row.status === '0' ? '1' : '0'
      })
  }

  /////////////////////////////////////////////////////
  /*抽屉区域*/
  const handleOpenScopeDrawer = async (row: any) => {
    roleScopeDrawerRef.value.show(row) /*初始化对话框中的表单信息*/
  }

  const handleAuthUser = (row: any) => {
    const roleId = row.roleId
    console.log(row)
    $router.push('/system/role-auth/user/' + roleId)
  }

  // 导出角色
  const handleExport = () => {}

  onMounted(() => {
    getRoleListPage() //获取第一页的信息
    setTimeout(() => {
      loading.value = false
    }, 500)
  })
</script>

<script lang="ts">
  export default {
    dicts: ['sys_normal_disable'],
  }
</script>

<style scoped lang="scss">
  .header {
    display: flex;
    padding: 16px 16px 0px 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  }

  .footer {
    flex: 1;
    display: flex;
    padding: 16px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    position: relative;
    box-sizing: border-box;

    .util {
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-end;
      flex-shrink: 0;
    }

    .table-inner {
      flex: 1;
      position: relative;
    }

    .table {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }
</style>
